package com.century.sjt.activity.login;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.widget.EaseSidebar;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.adapter.ItemMoreAdapter;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by 炳基 on 2016/8/22.
 */
public class ChooseLanguageActivity extends BaseActivity {

    private SjtTitleBar titleBar;
    private ListView mList;
    private Boolean isDataChangeOk=true;
    private List<Map<String, Object>> dataList;
    private ItemMoreAdapter adapter;
    protected EaseSidebar sidebar;
    private String mType = "0";
    SharedPreferences mainSharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosecountry);
        initView();
        initEvent();
        if (getIntent().getStringExtra("type")!=null){
            mType = getIntent().getStringExtra("type");
        }
    }
    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_choose_languge));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        titleBar.setRightIconResourc(getResources().getString(R.string.btn_yes));
        mList = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);
        sidebar.setVisibility(View.GONE);
    }

    @Override
    protected void initEvent() {
        dataList = new ArrayList<Map<String, Object>>();
        adapter = new ItemMoreAdapter(ChooseLanguageActivity.this,dataList,"language");
        mList.setAdapter(adapter);
        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map map = (Map) dataList.get(i);
                String name = (String) map.get("name");
                String code = (String)map.get("code");
                if ("Translate".equals(mType)){
                    setTransLanguage(code,name);
                }else {
                    PreferenceManager.getInstance().setLanguageCode(code);
                    PreferenceManager.getInstance().setCurrentLanguage(name);
                    Intent intent = new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putString("languageName", name);
                    bundle.putString("languageCode", code);
                    intent.putExtras(bundle);
                    ChooseLanguageActivity.this.setResult(RESULT_OK, intent);
                    switch (mType){
                        case "register":
                            finish();
                            break;
                        case "login":
                            finish();
                            break;
                        default:
                            startActivity(new Intent(ChooseLanguageActivity.this, LoginActivity.class));
                            break;
                    }
                }



            }
        });
        sidebar.setListView(mList);
//
    }

    @Override
    protected void initData() {
        switch (mType){
            case "Translate":
                getTranslateLanguage();
                break;
            default:
                getLanguage();
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getLanguage();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    private void getLanguage(){
        Locale locale = getResources().getConfiguration().locale;
        final String language = locale.getLanguage();
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getLanguage, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        dataList.clear();
                        JSONObject Data = res.getJSONObject("data");
                        JSONArray countryList = Data.getJSONArray("languageList");
                        for (int i = 0; i < countryList.length(); i++) {
                            JSONObject aData = (JSONObject) countryList.get(i);
                            String LanguageCode = aData.getString("languageCode");
                            String LanguageName = aData.getString("nativeName");
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("name", LanguageName);
                            map.put("code", LanguageCode);
                            dataList.add(map);
                        }
                    } else {//失败
                        TipUtil.showToast(message, ChooseLanguageActivity.this, 1);
                    }
//                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseLanguageActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseLanguageActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
                map.put("code", language);

                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    private void getTranslateLanguage(){
        Locale locale = getResources().getConfiguration().locale;
        final String language = locale.getLanguage();
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getTranslateLanguage, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        dataList.clear();
                        JSONObject Data = res.getJSONObject("data");
                        JSONArray countryList = Data.getJSONArray("languageList");
                        for (int i = 0; i < countryList.length(); i++) {
                            JSONObject aData = (JSONObject) countryList.get(i);
                            String LanguageCode = aData.getString("languageCode");
                            String nativeName = aData.getString("nativeName");
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("name", nativeName);
                            map.put("code", LanguageCode);
                            dataList.add(map);
                        }
                    } else {//失败
                        TipUtil.showToast(message, ChooseLanguageActivity.this, 1);
                    }
//                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseLanguageActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseLanguageActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("code", language);

                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    private void setTransLanguage(final String mcode,final String name){

//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.setTransLanguage, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        SharedPreferences.Editor editor = mainSharedPreferences.edit();
                        editor.putString("transLanguage", mcode);
                        editor.commit();
                        Intent intent = new Intent();
                        Bundle bundle=new Bundle();
                        bundle.putString("languageName", name);
                        bundle.putString("languageCode", mcode);
                        intent.putExtras(bundle);
                        ChooseLanguageActivity.this.setResult(RESULT_OK, intent);
                        finish();
                    } else {//失败
                        TipUtil.showToast(message, ChooseLanguageActivity.this, 1);
                    }
//                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseLanguageActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseLanguageActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("code", mcode);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
}
